<script setup>
import Project from "./project.vue";
import { GetListAPI } from "@/api/device/equipment";
import {
  getDownUserAPI,
  GetTeaListAPI,
} from "@/api/device/maintenance/workorder.js";
import { GetViewAPI } from "@/api/system/team";

import { GetDeviceDdlAPI } from "@/api/device/maintenance/project.js";

// vue3方法实例
const { proxy } = getCurrentInstance();

const { sys_project_type } = proxy.useDict("sys_project_type");
// 子传父
const emit = defineEmits();

// 父传子
const props = defineProps({
  isShow: {
    type: Boolean,
    default: false,
  },
  //   传入数据 用于回显
  data: {
    type: Object,
    default: () => {},
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false,
  },
  //   传入数据 弹窗标题
  title: {
    type: String,
    default: "新增",
  },
});

// 标签页字段
const activeName = ref("计划信息");

const ruleFormRef = ref(null);

// 维保项目弹窗
const projectShow = ref(false);

// 维保项目勾选数据
const tabelSel = ref([]);

// 设备台账列表
const deviceSel = ref([]);

// 班组信息列表
const teamSel = ref([]);
// 表单字段
const ruleForm = reactive({
  knowledgeCode: "",
  knowledgeName: "",
  deviceId: "",
  maintenanceProjects: [],
  knowledgeFailureType: 0,
  knowledgeFailureDescription: "",
  knowledgeFailurePicture: "",
  knowledgeFailureAnalysis: "",
  knowledgeFailureProcess: "",
  maintenanceNumberPeoplea: [],
  maintenanceNumberPeopleOption: [],
  deviceCode: "",
  maintenanceManagerId: "",
  maintenanceProjectList: [],
});

// 自定义验证
const checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请填写计划配置项"));
  }
};
// 表单校验
const rules = reactive({
  deviceCode: [
    { required: true, message: "请选择设备编号", trigger: "change" },
  ],
  groupId: [{ required: true, message: "请填写班组", trigger: "blur" }],
  time: [{ required: true, message: "请选择时间", trigger: "change" }],
  auditOpinion: [
    { required: true, message: "请填写审核意见", trigger: "blur" },
  ],
  projectType: [{ required: true, message: "请选择项目类型", trigger: "blur" }],
});

// 添加维保项目
const addProject = (val) => {
  ruleForm.maintenanceProjects.push(...val);
  projectShow.value = false;
};

// 设备 选择下拉带出相应数据
const deviceCodeChange = (val) => {
  const result = deviceSel.value.find((item) => item.deviceCode == val);
  if (result) {
    ruleForm.deviceName = result.deviceName;
    ruleForm.deviceType = result.deviceType;
    ruleForm.deviceUnitType = result.deviceUnitType;
    ruleForm.installationLocation = result.installationLocationName;
    ruleForm.deviceId = result.id;
  }
};

// 获取维保人员和维保负责人下拉数据
const getDownUser = async () => {
  const res = await getDownUserAPI();
  ruleForm.maintenanceNumberPeopleOption = res;
};

// 提交方法
const submit = async () => {
  const valid = await ruleFormRef.value.validate();
  if (!valid) return false;
  if (ruleForm.time) {
    ruleForm.maintenanceStartTime = ruleForm.time[0];
    ruleForm.maintenanceEndTime = ruleForm.time[1];
  }
  return ruleForm;
};

// 勾选数据
const handleSelectionChange = (rows) => {
  tabelSel.value = rows;
};

/**
 * 班组下拉
 */
// 获取班组
const getTeamSel = async () => {
  const { data: res } = await GetTeaListAPI();

  teamSel.value = res;
};

// 获取设备列表信息
const getDeviceSel = async () => {
  const { data: res } = await GetDeviceDdlAPI();
  deviceSel.value = res;
};

/**
 * 选择班组
 */
const teamsChange = async (id) => {
  const result = teamSel.value.filter((t) => t.teamId == id)[0] || {};
  ruleForm.maintenanceNumberPeoplea = result.personnelList.map((t) => t.value);
  console.log(result);
  ruleForm.personnelList = result.personnelList;
  ruleForm.groupName = result.teamName;

  ruleForm.maintenanceManagerId = result.leaderId;
};

// 监听回显
const initData = async () => {
  if (props.data?.id) {
    Object.keys(props.data).forEach(
      (itemKey) => (ruleForm[itemKey] = props.data[itemKey])
    );
    if (ruleForm.maintenanceStartTime)
      ruleForm.time = [
        ruleForm.maintenanceStartTime,
        ruleForm.maintenanceEndTime,
      ];
    ruleForm.maintenanceProjectList = ruleForm.maintenanceProjectList
      ? ruleForm.maintenanceProjectList
      : ruleForm.workOrderProjectList;
    // teamsChange(ruleForm.groupId)
    if (props.title != "派工") {
      if (ruleForm.groupMemberList?.length > 0)
        ruleForm.maintenanceNumberPeoplea = ruleForm.groupMemberList.map(
          (item) => String(item.id)
        );
    }
  }
  if (props.title == "派工") {
    getDownUser();
    getTeamSel();
    // ruleForm.personnelList = result.personnelList

    // ruleForm.maintenanceManagerId = result.leaderId
  } else {
    if (props.title == "查看" || props.title == "审核") {
      console.log(ruleForm, "ruleForm");
      ruleForm.groupId = ruleForm.groupName;
      ruleForm.maintenanceManagerId = ruleForm.chargePerson;
      ruleForm.maintenanceNumberPeoplea = ruleForm.groupMemberList.map(
        (t) => t.name
      );
    }
    getDeviceSel();
  }
};

initData();
const remove = (scope) => {
  if (tabelSel.value.length > 0) {
    tabelSel.value.forEach((item) => {
      const Find = ruleForm.maintenanceProjects.findIndex(
        (itemy) => item.id == itemy.id
      );
      ruleForm.maintenanceProjects.splice(Find, 1);
    });
  } else {
    if (ruleForm.maintenanceProjects?.length < 1) return;
    ruleForm.maintenanceProjects.splice(
      ruleForm.maintenanceProjects.length - 1,
      1
    );
  }
};

// 计算共和
const total = computed(() => {
  let total = 0;
  if (
    Array.isArray(ruleForm.maintenanceProjects) &&
    ruleForm.maintenanceProjects?.length > 0
  ) {
    ruleForm.maintenanceProjects.forEach((item) => (total += item.workingHour));
  }
  return total;
});

// 导出方法
defineExpose({ submit });
</script>
<template>
  <div class="title" v-if="props.title != '派工'">工单信息</div>
  <el-divider v-if="props.title != '派工'" />
  <el-form
    inline
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    status-icon
  >
    <div v-if="props.title != '派工'">
      <el-form-item label="维保单号" v-if="props.disabled">
        <el-input
          clearable
          v-model="ruleForm.maintenanceNumber"
          disabled
          placeholder="请填写项目名称"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceCode">
        <el-select
          :disabled="props.title != '修改' && props.title != '新增'"
          v-model="ruleForm.deviceCode"
          filterable
          placeholder="请选择设备编号"
          @change="deviceCodeChange"
        >
          <el-option
            v-for="item in deviceSel"
            :key="item.deviceCode"
            :label="item.deviceCode"
            :value="item.deviceCode"
          >
            <span style="float: left">{{ item.deviceName }}</span>
            <span
              style="
                float: right;
                margin-left: 5px;
                color: var(--el-text-color-secondary);
                font-size: 13px;
              "
              >{{ item.deviceCode }}</span
            >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="设备类型">
        <el-input
          clearable
          disabled
          v-model="ruleForm.deviceType"
          placeholder=""
        />
      </el-form-item>
      <el-form-item label="设备型号">
        <el-input
          clearable
          disabled
          v-model="ruleForm.deviceUnitType"
          placeholder=""
        />
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input
          clearable
          v-model="ruleForm.deviceName"
          disabled
          placeholder=""
        />
      </el-form-item>
      <el-form-item label="位置">
        <el-input
          clearable
          v-model="ruleForm.installationLocation"
          disabled
          placeholder=""
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <p-select
          :option="sys_project_type"
          :disabled="props.disabled"
          v-model="ruleForm.projectType"
          placeholder="请选择项目类型"
        />
      </el-form-item>
      <div class="rk" v-if="props.title == '审核'">
        <el-form-item label="审核意见">
          <el-input
            type="textarea"
            clearable
            v-model="ruleForm.auditOpinion"
            placeholder="请填写审核意见"
          />
        </el-form-item>
      </div>
    </div>

    <!-- 维保人员 -->
    <div v-if="props.title != '新增'">
      <div class="title">维保人员</div>
      <el-divider />
      <el-form-item label="班组" prop="groupId">
        <el-select
          v-model="ruleForm.groupId"
          placeholder="请选择维班组"
          :disabled="props.title != '派工' && props.title != '修改'"
          @change="teamsChange"
          style="width: 240px"
        >
          <el-option
            v-for="item in teamSel"
            :key="item.value"
            :label="item.teamName"
            :value="item.teamId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维保负责人">
        <p-select
          v-model="ruleForm.maintenanceManagerId"
          disabled
          :option="ruleForm.maintenanceNumberPeopleOption"
          placeholder="请选择维保负责人"
        />
      </el-form-item>
      <el-form-item label="维保人员">
        <p-select
          multiple
          v-model="ruleForm.maintenanceNumberPeoplea"
          :disabled="props.title != '派工' && props.title != '修改'"
          :option="ruleForm.personnelList"
          placeholder="请选择维保人员"
        />
      </el-form-item>

      <el-form-item
        v-if="props.title == '查看' || props.title == '审核'"
        label="图片"
        style="width: 100%"
      >
        <p-imagePreview
          :src="
            JSON.parse(ruleForm.fileImagePath)
              ?.map((t) => t.url)
              ?.join(',') || ''
          "
        />
      </el-form-item>
    </div>
    <div v-if="props.title == '新增'">
      <div class="title">维保项目</div>

      <div class="flex-items-center flex-between">
        <div class="title"></div>

        <div class="flex" v-if="!props.disabled">
          <el-tooltip
            class="box-item"
            effect="dark"
            content="添加前请选择项目类型"
            placement="top-start"
          >
            <el-icon @click="projectShow = ruleForm.projectType ? true : false">
              <Plus />
            </el-icon>
          </el-tooltip>
          <div style="margin: 0 10px"></div>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="勾选删除"
            placement="top-start"
          >
            <el-icon @click="remove">
              <Minus />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
      <!-- 表格数据 -->
      <el-table
        stripe
        border
        :data="ruleForm.maintenanceProjects"
        style="margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column label="序号" width="70" type="index" />
        <!-- <el-table-column
          label="项目编号"
          prop="maintenanceProjectCode"
          width="180"
          align="center"
          show-overflow-tooltip
        /> -->
        <el-table-column
          label="项目名称"
          prop="maintenanceProjectName"
          width="180"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="维保部位"
          prop="maintenancePosition"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="计划指令"
          prop="paleInstructStr"
          width="180"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="维保内容"
          prop="maintenanceContent"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="备件或耗材型号"
          prop="consumables"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="保养数量"
          prop="maintenanceNum"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="保养级别"
          prop="maintenanceLevelDict"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="标准工时"
          prop="workingHour"
          width="120"
          align="center"
          show-overflow-tooltip
        />

        <el-table-column
          label="备注"
          prop="remark"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
      </el-table>
      <div class="total">
        总工时：
        {{ total }}
      </div>
    </div>

    <!-- 维保项目 -->
    <div v-if="props.title != '新增' && props.title != '派工'">
      <div class="title">维保项目</div>
      <el-divider />
      <div class="rk">
        <el-form-item label="维保起止时间" prop="time">
          <!-- <el-date-picker
            clearable
            :disabled="props.title != '执行维保' && props.title != '修改'"
            v-model="ruleForm.time"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="-"
            type="datetimerange"
            start-placeholder="请选择维保开始时间"
            end-placeholder="请选择维保结束时间"
          /> -->
          开始时间：{{ ruleForm.maintenanceStartTime }} - 结束时间 ：{{
            ruleForm.maintenanceEndTime
          }}
        </el-form-item>
      </div>

      <el-table
        stripe
        border
        :data="ruleForm.maintenanceProjectList"
        style="margin-top: 10px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column
          label="项目名称"
          prop="maintenanceProjectName"
          width="180"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="维保部位"
          prop="maintenancePosition"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="计划指令"
          prop="paleInstructs"
          width="180"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="维保内容"
          prop="maintenanceContent"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="备件或耗材型号"
          prop="consumables"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="保养数量"
          prop="maintenanceNum"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="保养级别"
          prop="maintenanceLevel"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="标准工时"
          prop="workingHour"
          width="120"
          align="center"
          show-overflow-tooltip
        />

        <el-table-column
          label="项目备注"
          prop="remark"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="实际指令"
          prop="actualInstruction"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="执行备注"
          prop="actualInstruction"
          width="auto"
          align="center"
          show-overflow-tooltip
        />
      </el-table>
    </div>
  </el-form>

  <!-- 维保项目 -->
  <Project
    :bdb="false"
    :is-show="projectShow"
    @preservation="addProject"
    :deviceId="ruleForm.deviceId"
    :projectType="ruleForm.projectType"
    :ids="ruleForm.maintenanceProjects.map((t) => t.id) || []"
    @cancel="projectShow = false"
  />
</template>

<style lang="scss" scoped>
.rk ::v-deep .el-form-item {
  width: 100% !important;
}

.rk ::v-deep .el-date-editor {
  width: 40% !important;
}

.title {
  color: #3292fb;
}

.total {
  float: right;
  font-size: 16px;
  margin-top: 15px;
  margin-right: 15px;
}
</style>